<template>
	<view class="page">
		<template v-if="isLogin">
			<view class="body">
				<view class="env-params">
					<image class="bg-img" src="@/static/images/public_addinfo.png" mode="widthFix">
						<view class="contain">
							<view class="hd-title">环境数据</view>
							<view class="data-list ">
								<view class="item">
									<view class="label">经度</view>
									<text class="val">{{params.d2ms_lng||'--'}}</text>
								</view>
								<view class="item">
									<view class="label">纬度</view>
									<text class="val">{{params.d2ms_lat||'--'}}</text>
								</view>
								<!-- <view class="item">
									<view class="label">精度</view>
									<text class="val">{{params.accuracy|toFixedN(2)||'--'}} m</text>
								</view> -->
								<view class="item">
									<view class="label">海拔</view>
									<text class="val">{{params.altitude|toFixedN(2)||'--'}}m</text>
								</view>
								<view class="item">
									<view class="label">天气情况</view>
									<text class="val">{{params.weather||'--'}}</text>
								</view>
								<view class="item">
									<view class="label">空气温度</view>
									<text class="val">{{params.temperature||'--'}}°c</text>
								</view>
								<view class="item">
									<view class="label">空气湿度</view>
									<text class="val">{{params.humidity||'--'}}%</text>
								</view>
							</view>

							<view class="local-area">
								<view class="icon iconfont icon-daohang f-s40">&#xe648;</view>
								<view class="text">{{params.address}}</view>
							</view>
						</view>
				</view>

				<!-- 图片上传 -->
				<view class="form-wrap m-b2">
					<view class="upload-pic-item">
						<view class="title-bar">
							<view class="label">现场拍照</view>
							<navigator open-type="navigate"
								url="/pages/webview/webview?page_type=article&title=红火蚁介绍&url=https://mp.weixin.qq.com/s/knWkYOaQpZ5wSVuvp1WfJA"
								hover-class="none" class="link-btn">认识红火蚁</navigator>
						</view>
						<view class="form-upload-pic">
							<template>
								<view class="img-item" v-for="(item,index) in params.files" :key="index">
									<image src="@/static/images/filter_bg.png" mode="widthFix">
										<!-- 占位 -->
									</image>
									<view class="img-wrap" @click="previewPic(index)">
										<image class="img" :src="item.url" mode="widthFix"></image>
									</view>
									<view class="del-icon" @click="delPic(index)">
										<view class="iconfont">&#xe74b;</view>
									</view>
									<view v-if="item.status==0" class="loading-img">
										<div class="loading-icon loader-18"></div>
									</view>
								</view>
							</template>
							<view class="img-item add-btn" @click="uploadImage">
								<image src="@/static/images/upload_pic.png" mode="widthFix"></image>
							</view>

							<view class="img-item">
								<image src="@/static/images/filter_bg.png" mode="widthFix">
									<!-- 占位 -->
								</image>
								<view class="img-wrap" @click="previewDemoPic(index)">
									<image class="img" src="@/static/images/pai_example.jpg" mode="widthFix"></image>
								</view>
							</view>
						</view>
					</view>
				</view>

				<view class="form-wrap m-b2">
					<view class="form-item">
						<view class="label">联系电话：</view>
						<view class="form-input">
							<view class="content">
								<view class="inp f-grey">{{replace_phone}}</view>
							</view>
						</view>
					</view>

					<view class="form-item">
						<view class="label">蚁巢数：</view>
						<view class="form-input">
							<view class="content">
								<input type="number" class="inp" v-model="params.nests_count" placeholder="输入蚁巢数" />
								<view class="link">个</view>
							</view>
						</view>
					</view>

					<view class="form-textarea-item">
						<view class="label a-t">备注信息</view>
						<view class="form-textarea">
							<textarea class="inp-textarea" v-model="params.remark" placeholder="备注信息(选填),如省,市,区区域信息等"
								maxlength="-1"></textarea>
						</view>
					</view>
				</view>




			</view>

			<!-- 底部 -->
			<view class="footer">
				<view class="fix-wrap bottom">
					<view class="form-lay-btn" @click="submit">提交</view>
				</view>
			</view>


		</template>
	</view>
</template>

<script>
	import {
		uploadImage,
		previewImage,
		uploadToServe,
		checkPhone,
		replaceStr,
		d2Dms
	} from '@/common/util.js'
	import {
		gd_map_Key,
		tc_map_key,
		gd_map_Key_web,
		HTTP_REQUEST_URL
	} from '@/config.js'
	import {
		createdRules,
		fkSuccessTips
	} from '@/common/redPack.js'
	import {
		getSystemInfo
	} from '@/common/promise.js'
	export default {
		name: 'name',
		data() {
			return {
				isLogin: false,
				isStop: true,
				userInfo: uni.getStorageSync('userInfo'),
				pid: 0,
				replace_phone: '',
				params: {
					location: '',
					d2ms_lat: '',
					d2ms_lng: '',
					latitude: '',
					longitude: '',
					fid: 0,
					address: '',
					files: [],
					weather: '',
					temperature: '',
					humidity: '',
					altitude: '',
					speed: '',
					accuracy: '',
					nests_count: '',
					phone: '',
					remark: ''
				},
				web_host: HTTP_REQUEST_URL
			}


		},
		filters: {
			toFixedN: function(val, n) {
				val = Number(val);
				return val.toFixed(n);
			}
		},
		async onLoad(params) {
			this.isLogin = await this.$loginState('check');
			this.replace_phone = replaceStr(this.userInfo.phone, 3, '****');
			if (params.pid) {
				this.pid = params.pid;
			}

			if (this.isLogin) {
				this.getLocal();
				this.getUserInfo();
			}
		},
		async onShow() {

		},
		methods: {

			// 获取用户信息
			getUserInfo: async function() {
				let res = await this.$api.user_api.getUserInfo();
				if (res.data.ret == 0) {
					this.userInfo = res.data.data;
				}
			},

			// 监测当前位置是否可采集
			checkArea: async function(lat, lng) {
				let res = await this.$api.ssp_api.checkArea({
					lat: lat,
					lng: lng,
					is_app: 1
				})
				uni.showLoading({
					mask: true,
					title: '环境监测中...'
				})
				if (res.data.ret == -1) {
					uni.hideLoading();
					uni.showToast({
						icon: "none",
						title: res.data.message,
						mask: true,
						duration: 3000,
						success() {
							setTimeout(() => {
								uni.navigateBack({
									delta: 1
								})
							}, 3000)
						}
					})
					return false
				} else {
					uni.hideLoading();
					uni.showToast({
						icon: "none",
						title: '此处可以采集',
						mask: true,
						success() {}
					})
					return true
				}
			},

			// 获取当前位置信息
			getLocal: function() {

				let _this = this;
				uni.getLocation({
					type: 'gcj02',
					geocode: true,
					success: async function(res) {
						_this.params.d2ms_lat = d2Dms(parseFloat(res.longitude).toFixed(
							6)); // d2Dms方法 转为度分秒格式
						_this.params.d2ms_lng = d2Dms(parseFloat(res.latitude).toFixed(
							6)); // d2Dms方法 转为度分秒格式
						_this.params.latitude = res.latitude;
						_this.params.longitude = res.longitude;
						_this.params.altitude = res.altitude;
						_this.params.speed = res.speed;
						_this.params.accuracy = res.accuracy;

						_this.getCityInfo(res.latitude, res.longitude); // 根据坐标获取城市信息						

						_this.checkArea(res.latitude, res.longitude);

						uni.setStorage({
							key: 'local',
							data: {
								latitude: _this.params.latitude,
								longitude: _this.params.longitude
							}
						})

					},
					fail() {
						uni.hideLoading();
						uni.showToast({
							icon: "none",
							title: '获取位置失败',
							mask: true,
							duration: 2000,
							success() {}
						})
					}
				});
			},

			//获取天气信息
			getWeatherInfo: async function(adcode) {
				let res = await this.$api.ssp_api.getWeather({
					key: gd_map_Key_web,
					city: adcode
				})
				if (res != false && res.data.info == "OK") {
					if (res.data.lives.length > 0) {
						this.params.weather = res.data.lives[0].weather;
						this.params.temperature = res.data.lives[0].temperature;
						this.params.humidity = res.data.lives[0].humidity;
					}
				}

			},

			// 获取城市信息
			getCityInfo: async function(lat, lng) {
				let res = await this.$api.ssp_api.getCityInfo({
					key: tc_map_key,
					location: lat + ',' + lng
				})
				if (res.data.message == "query ok") {

					this.params.address = res.data.result.address_component.city + res.data.result.formatted_addresses
						.recommend;
					this.getWeatherInfo(res.data.result.ad_info.adcode); // 根据adcode 获取天气信息
				}
			},

			// 上传图片
			uploadImage: function() {
				// 上传现场照片
				let _this = this;
				let params = {
					lat: this.params.latitude,
					lng: this.params.longitude,
					location: this.params.location,
					address: this.params.address,
					weather: this.params.weather
				};
				// JSON.parse(decodeURIComponent(option.item));
				params = encodeURIComponent(JSON.stringify(params));
				uni.navigateTo({
					url: '/package_common/photograph/photograph?params=' + params,
					animationType: 'none'
				})

				// uploadImage({
				// 	length: _this.params.files.length,
				// 	maxSize: 1,
				// 	sourceType: ['camera'],
				// 	success(res) {
				// 		console.log(res)
				// 		let params_data = {};
				// 		params_data.status = 0;
				// 		params_data.url = res.tempFilePaths[0];
				// 		_this.params.files.push(params_data);
				// 		uploadToServe({
				// 			url: '/public/upload-file',
				// 			filePath: res.tempFilePaths[0],
				// 			name: 'photo',
				// 			formData: {
				// 				'p_id': _this.pid,
				// 				'uid': _this.userInfo.id
				// 			}
				// 		}).then((up_res) => {
				// 			console.log(up_res)
				// 			if (up_res.ret == 0) {
				// 				params_data.file_name = up_res.data.file_name;
				// 				params_data.file_path = up_res.data.file_path;
				// 				params_data.file_type = up_res.data.file_type;
				// 				params_data.status = up_res.data.status;
				// 				params_data.type = up_res.data.type;
				// 			}
				// 		})
				// 	}
				// })
			},

			upload_tpimg() {
				let params_data = {},
					_this = this;
				params_data.url = getApp().globalData.upload_img;
				params_data.status = 0;
				this.params.files.push(params_data);
				console.log('upload-img', params_data.url);

				uploadToServe({
					url: '/public/upload-file',
					filePath: params_data.url,
					name: 'photo',
					formData: {
						'p_id': _this.pid,
						'uid': _this.userInfo.id
					}
				}).then((up_res) => {
					console.log(up_res)
					if (up_res.ret == 0) {
						params_data.file_name = up_res.data.file_name;
						params_data.file_path = up_res.data.file_path;
						params_data.file_type = up_res.data.file_type;
						params_data.status = up_res.data.status;
						params_data.type = up_res.data.type;
					}
				})
			},

			// 预览图片
			previewPic: function(index) {
				let _this = this;
				let preview_data = [];
				this.params.files.forEach(item => {
					preview_data.push(item.url);
				})
				previewImage({
					data: preview_data,
					index: index
				})
			},

			// 预览示例图片
			previewDemoPic: function(index) {
				previewImage({
					data: [this.web_host + '/images/pai_example1.jpg'],
					index: index
				})
			},

			// 删除图片
			delPic: async function(index) {
				let res = await this.$api.ycj_api.deletefile({
					file_path: this.params.files[index].file_path
				})
				if (res.data.ret == 0) {
					this.params.files.splice(index, 1);
				}
			},

			//上传数据
			submit: async function() {
				let _this = this;
				let system = await getSystemInfo(); //  获取系统信息

				if (this.params.files.length == 0) {
					uni.showToast({
						icon: "none",
						title: '请拍照上传图片',
						mask: true
					})
					return
				}
				if (this.params.nests_count == '') {
					uni.showToast({
						icon: "none",
						title: '请输入蚁巢数',
						mask: true
					})
					return
				}

				let img_status = this.params.files.some(item => {
					if (item.status == 0) {
						return true
					}
				})

				if (img_status) {
					uni.showToast({
						icon: 'none',
						title: '图片未上传完',
						mask: true,
						duration: 1000
					})
					return
				}

				// 判断是否已绑定微信
				if (!this.userInfo.wx_uuid) {
					createdRules({
						systemInfo: system,
						msg: '正在进行随手拍作业领微信红包活动，请先授权微信绑定账号。'
					})
					return
				}

				if (this.isStop) {
					this.isStop = false;
					this.submitEvent();
				}

			},

			submitEvent: async function() {
				let _this = this;
				let system = await getSystemInfo(); //  获取系统信息
				uni.showLoading({
					title: '正在提交数据',
				})

				let res = await this.$api.ssp_api.addData({
					'pro_id': this.pid,
					'nests_count': this.params.nests_count,
					'phone': this.userInfo.phone,
					'files': JSON.stringify(this.params.files),
					'accuracy': this.params.accuracy,
					'gcj02_lat': this.params.latitude,
					'gcj02_lng': this.params.longitude,
					'altitude': this.params.altitude,
					"weather": this.params.weather,
					"temperature": this.params.temperature,
					"humidity": this.params.humidity,
					'address': this.params.address,
					"remark": this.params.remark
				})

				if (res.data.ret == 0) {
					uni.hideLoading();
					uni.showToast({
						icon: "success",
						title: '数据提交成功',
						mask: true,
						duration: 2000,
						success() {
							_this.updateCollectData();
						}
					})

				} else {
					uni.hideLoading();
					uni.showToast({
						icon: "none",
						image: '../../static/images/error.png',
						title: '数据提交失败',
						mask: true,
						success() {
							setTimeout(() => {
								_this.isStop = true;
							}, 300)
						}
					})
				}

			},

			// 更新数据
			updateCollectData: async function() {
				let _this = this;
				let updateState = 0;
				let system = await getSystemInfo(); //  获取系统信息

				uni.showLoading({
					title: '数据更新中...',
					mask: true
				})

				// 更新城市编码
				let a_res = await this.$api.ssp_api.updateAdcode();
				console.log(a_res)
				if (a_res.data.ret == 0) {
					updateState += 1;
				} else {
					uni.hideLoading();
					uni.showToast({
						icon: "success",
						title: '城市编码更新失败',
						mask: true,
						duration: 2000,
						success() {

						}
					})
					return
				}

				if (updateState == 1) {
					uni.hideLoading();
					uni.showToast({
						icon: 'success',
						title: '数据更新成功',
						mask: true,
						duration: 1000,
						success() {
							setTimeout(() => {
								_this.isStop = true;
								fkSuccessTips({
									systemInfo: system
								})
							}, 1300)
						}
					})

				} else {
					uni.showToast({
						icon: "error",
						title: '数据更新成功',
						mask: true,
						duration: 2000,
						success() {}
					})
				}

				return

				setTimeout(async function() {
					let s_res = await this.$api.ssp_api.sspfp();
					console.log(s_res)
					if (s_res.data.ret == 0) {
						updateState += 1;
					} else {
						uni.hideLoading();
						uni.showToast({
							icon: "success",
							title: '数据提交成功',
							mask: true,
							duration: 2000,
							success() {
								_this.updateCollectData();
							}
						})
						return
					}

					if (updateState == 1) {
						_this.isStop = true;
						uni.showToast({
							icon: 'success',
							title: '数据更新成功',
							mask: true,
							duration: 1000,
							success() {
								fkSuccessTips({
									systemInfo: system
								})
							}
						})

					} else {
						uni.showToast({
							icon: "success",
							title: '数据提交成功',
							mask: true,
							duration: 2000,
							success() {}
						})
					}

				}, 1000);



			},

			updateAdcode: function() {

			}

		},
		components: {},

		computed: {
			userInfoStatus() {
				return this.$store.state.userInfoStatus;
			}
		},
		watch: {
			userInfoStatus(newer, older) {
				if (newer) {
					this.getUserInfo();
					this.submitEvent();
				}
			}
		}

	}
</script>

<style lang="less">
	.title-bar {
		position: relative;

		.link-btn {
			position: absolute;
			right: 0;
			top: 0;
			padding: 3rpx 5rpx;
			background: linear-gradient(to right, #fe5d55, #e2231a);
			border-radius: 8rpx;
			color: #fff;
			font-size: 30rpx;
		}
	}

	.env-params {
		position: relative;

		.contain {
			position: absolute;
			left: 0;
			top: 0;
			width: 100%;
			height: 100%;
		}

		.hd-title {
			margin: 80rpx 20rpx 10rpx;
			padding-left: 20rpx;
			border-left: 10rpx solid #f8a53f;
			font-size: 32rpx;
			font-weight: bold;
			color: #fff;
		}
	}

	.data-list {
		display: flex;
		flex-wrap: wrap;
		justify-content: space-between;
		width: 94%;
		margin: 0 auto 10rpx;

		.item {
			width: 33%;
			margin-top: 30rpx;
			font-size: 28rpx;
			text-align: center;
			color: #fff;

			.label {
				margin-bottom: 10rpx;
				color: #fff;
			}
		}
	}

	.local-area {
		display: flex;
		width: 85%;
		margin: 50rpx auto;
		background: #f2a6b2;
		border-radius: 8rpx;

		.icon {
			flex-shrink: 0;
			width: 70rpx;
			height: 80rpx;
			text-align: center;
			line-height: 80rpx;
			color: #fff;
		}

		.text {
			padding: 15rpx 0 15rpx 0;
			color: #fff;
			font-size: 30rpx;
		}
	}
</style>
